import serial
import serial.tools.list_ports 

# UART Command Table (See README for details)
TEMP_CMD  = 'T'
PHOTO_CMD = 'P'

class nox:
    """A Python lib for quickly access NOX Kit via UART under single board mode.

    Usage Example:

        from nox import nox

        # get available ports
        nox.ports()

        # make a new connection
        device = nox(port)

        # read ADC temperature or ADC photoresistor
        device.temp()
        device.photo()

    For developers:
    Use private method `__send_char' and `__read_hex' to extend the functionality. 
    """
    
    def __init__(self, port, baudrate=115200):
        self.ser = serial.Serial(port, baudrate)

    @classmethod
    def ports(cls):
        """List all the possible ports.

        Args:

        Returns:
            array: An array of possible ports device name.
        """
        return map(lambda p: p.device, serial.tools.list_ports.comports())

    def __send_char(self, char):
        """Send char to NOX Kit under sigle board mode.

        Args:
            char: Sending char

        Returns:
        """
        self.ser.write(bytes(char, 'utf-8'))

    def __read_hex(self, length=4):
        """Read input as literal hex from NOX Kit under single board mode.

        Args:
            length (default=4): Length of reading bytes.

        Returns:
            int: The hex number.
        """
        hex_str = self.ser.read(length).decode('utf-8')
        return int(hex_str, 16)

    def temp(self):
        """Read tempertuare from NOX Kit under single board mode.

        Args:

        Returns:
            int: The ADC temperature from NOX Kit.
        """
        self.__send_char(TEMP_CMD)
        return self.__read_hex()

    def photo(self):
        """Read photoresistor from NOX Kit under single board mode.

        Args:

        Returns:
            int: The ADC photoresistor from NOX Kit."""
        self.__send_char(PHOTO_CMD)
        return self.__read_hex()
